//
//  String+BoundingRect.swift
//  
//
//  Created by tangbl93 on 2021/1/8.
//

import UIKit

public extension String {
    
    func yx_boundingWidth(constraint height:CGFloat = .greatestFiniteMagnitude) -> CGFloat {
        return yx_boundingRect(height: height).width
    }
    
    func yx_boundingHeight(constraint width:CGFloat = .greatestFiniteMagnitude) -> CGFloat {
        return yx_boundingRect(width: width).height
    }
    
    func yx_boundingRect(fontSize:CGFloat = 15, width:CGFloat = CGFloat.greatestFiniteMagnitude, height:CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
        return yx_boundingRect(font: UIFont.systemFont(ofSize: fontSize), constraint: width, height: height)
    }
    
    func yx_boundingRect(font:UIFont, constraint width:CGFloat = CGFloat.greatestFiniteMagnitude, height:CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font]
        let constraintSize = CGSize(width: width, height: height)
        let options:NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
        let boundingRect = NSString(string: self).boundingRect(with: constraintSize, options: options, attributes: attributes, context: nil)
        return CGSize(width: ceil(boundingRect.width), height: ceil(boundingRect.height))
    }
}

public extension NSAttributedString {
    
    func yx_boundingWidth(constraint height:CGFloat = .greatestFiniteMagnitude) -> CGFloat {
        return yx_boundingRect(height: height).width
    }
    
    func yx_boundingHeight(constraint width:CGFloat = .greatestFiniteMagnitude) -> CGFloat {
        return yx_boundingRect(constraint: width).height
    }
    
    func yx_boundingRect(constraint width:CGFloat = CGFloat.greatestFiniteMagnitude, height:CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize {
        let options:NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
        let boundingRect = self.boundingRect(with: CGSize(width: width, height: height), options: options, context: nil)
        return CGSize(width: ceil(boundingRect.width), height: ceil(boundingRect.height))
    }
}
